package com.qyhl.webtv.commonlib.utils.share;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.basiclib.utils.network.model.ApiResult;
import com.qyhl.webtv.commonlib.R;
import com.qyhl.webtv.commonlib.base.BaseUrl;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.service.IntergralService;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.config.AppConfigUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import es.dmoral.toasty.Toasty;

/**
 * 分享工具类
 *
 * @author qyhl
 * @date 2017/11/21
 */
public class ShareUtils {
    private static final ShareUtils share = new ShareUtils();
    //剪切板管理工具类
    private ClipboardManager cm;
    //剪切板Data对象
    private ClipData mClipData;


    @Autowired(name = ServicePathConstant.INTERGRAL_SERICE)
    public IntergralService intergralService;

    private ShareUtils() {
        ARouter.getInstance().inject(this);
    }

    public static ShareUtils getInstance() {
        return share;
    }

    /**
     * @param context
     * @param URL         分享链接
     * @param title       分享标题
     * @param description 分享描述
     * @param listener    回调接口
     */
    public void doShare(final Activity context, final String URL, String title, String img, String description, final UMShareListener listener) {
        UMImage thumb;
        if (StringUtils.isEmpty(img)) {
            thumb = new UMImage(context, CommonUtils.getInstance().getAppLauncherIcon());
        } else if (img.equals("http://webtv.i2863.com/" + CommonUtils.getInstance().getSiteName() + "/")
                || img.equals("http://webtv.ccsobey.com/" + CommonUtils.getInstance().getSiteName() + "/")
                || img.equals("http://webtv1.ccsobey.com/" + CommonUtils.getInstance().getSiteName() + "/")) {
            thumb = new UMImage(context, CommonUtils.getInstance().getAppLauncherIcon());
        } else {
            thumb = new UMImage(context, img);
        }
        final UMWeb web = new UMWeb(URL);
        web.setTitle(title);//标题
        web.setThumb(thumb);  //缩略图
        if (StringUtils.isEmpty(description)) {
            description = " ";
        }
        Log.i("@@description", description);
        web.setDescription(description);//描述
        ShareBoardConfig config = new ShareBoardConfig();
        config.setShareboardPostion(ShareBoardConfig.SHAREBOARD_POSITION_BOTTOM);
        config.setIndicatorVisibility(false);
        config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_CIRCULAR);
        config.setCancelButtonVisibility(false);

        new ShareAction(context)
                .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .addButton("umeng_share_link", "umeng_share_link", "share_link", "share_link")
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (share_media == null) {
                            //根据key来区分自定义按钮的类型，并进行对应的操作
                            if ("umeng_share_link".equals(snsPlatform.mKeyword)) {
                                cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                //创建一个新的文本clip对象
                                mClipData = ClipData.newPlainText("share_link", URL);
                                //把clip对象放在剪贴板中
                                cm.setPrimaryClip(mClipData);
                                Toast.makeText(context, "复制成功！",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else {//社交平台的分享行为
                            new ShareAction(context)
                                    .setPlatform(share_media)
                                    .setCallback(listener)
                                    .withMedia(web)
                                    .share();
                        }
                    }
                })
                .open(config);
    }


    /**
     * 单个分享
     *
     * @param type        分享平台
     * @param context     上下文对象
     * @param URL         分享链接
     * @param title       分享标题
     * @param img         分享图片
     * @param description 分享简介
     * @param listener    回调接口
     */
    public void doSingleShare(String type, Activity context, String URL, String title, String img, String description, UMShareListener listener) {
        UMImage thumb;
        if (StringUtils.isEmpty(img)) {
            thumb = new UMImage(context, CommonUtils.getInstance().getAppLauncherIcon());
        } else if (img.equals("http://webtv.i2863.com/" + CommonUtils.getInstance().getSiteName() + "/")
                || img.equals("http://webtv.ccsobey.com/" + CommonUtils.getInstance().getSiteName() + "/")
                || img.equals("http://webtv1.ccsobey.com/" + CommonUtils.getInstance().getSiteName() + "/")) {
            thumb = new UMImage(context, CommonUtils.getInstance().getAppLauncherIcon());
        } else {
            thumb = new UMImage(context, img);
        }
        UMWeb web = new UMWeb(URL.trim());
        web.setTitle(title);//标题
        web.setThumb(thumb);  //缩略图
        if (StringUtils.isEmpty(description)) {
            description = " ";
        }
        web.setDescription(description);//描述

        switch (type) {
            case "QQ":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.QQ)
                        .setCallback(listener).share();
                break;
            case "QZ":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.QZONE)
                        .setCallback(listener).share();
            case "WeiXin":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(listener).share();
                break;
            case "Circle":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(listener).share();
                break;
            case "Link":
                cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                //创建一个新的文本clip对象
                mClipData = ClipData.newPlainText("share_link", URL);
                //把clip对象放在剪贴板中
                cm.setPrimaryClip(mClipData);
                Toast.makeText(context, "复制成功！",
                        Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

    }

    public void doSingleShare(String type, Activity context, String URL, String title, int img, String description, UMShareListener listener) {
        UMWeb web = new UMWeb(URL.trim());
        web.setTitle(title);//标题
        web.setThumb(new UMImage(context, img));  //缩略图
        if (StringUtils.isEmpty(description)) {
            description = " ";
        }
        web.setDescription(description);//描述

        switch (type) {
            case "QQ":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.QQ)
                        .setCallback(listener).share();
                break;
            case "QZ":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.QZONE)
                        .setCallback(listener).share();
                break;
            case "WeiXin":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(listener).share();
                break;
            case "Circle":
                new ShareAction(context)
                        .withMedia(web)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(listener).share();
                break;
            case "Link":
                cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                //创建一个新的文本clip对象
                mClipData = ClipData.newPlainText("share_link", URL);
                //把clip对象放在剪贴板中
                cm.setPrimaryClip(mClipData);
                Toast.makeText(context, "复制成功！",
                        Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

    }

    /**
     * 获取分享链接
     *
     * @param newsId 新闻id
     * @param type   新闻类型:  1 普通新闻 直播 2 图片新闻 3 推荐普通新闻 4 小视频 5电商 6,图文 7.互动 8.链接 9.内容 10.乡镇
     *               11.政务 12.专题 13.电台音频 14.电视视频 15.圈子 16.cms视频新闻 17.开票有喜 18.开票有喜(底部)
     * @return
     */
    public void getShareUrl(final String newsId, final int type, final ShareCallBack shareCallBack) {

        //获取分享地址


        EasyHttp.get(BaseUrl.GET_NEW_SHARE_URL)
                .params("siteId", CommonUtils.getInstance().getSite() + "")
                .params("tagName", CommonUtils.getInstance().getSiteName())
                .params("newsId", newsId)
                .params("type", type + "")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        shareCallBack.getUrlCallBack(false, e.getCode() + "");
                    }

                    @Override
                    public void onSuccess(String s) {
                        Log.i("@@@", s);
                        ApiResult bean = new Gson().fromJson(s, ApiResult.class);
                        shareCallBack.getUrlCallBack(true, bean.getData().toString());
                    }
                });

    }

    public void getShareUrl(final String newsId, final String contentId, final int type, final ShareCallBack shareCallBack) {

        //获取分享地址


        EasyHttp.get(BaseUrl.GET_NEW_SHARE_URL)
                .params("siteId", CommonUtils.getInstance().getSite() + "")
                .params("tagName", CommonUtils.getInstance().getSiteName())
                .params("newsId", newsId)
                .params("contentId", contentId)
                .params("type", type + "")
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        shareCallBack.getUrlCallBack(false, e.getCode() + "");
                    }

                    @Override
                    public void onSuccess(String s) {
                        Log.i("@@@", s);
                        ApiResult bean = new Gson().fromJson(s, ApiResult.class);
                        shareCallBack.getUrlCallBack(true, bean.getData().toString());
                    }
                });

    }

    /**
     * 分享
     *
     * @param newsId  id
     * @param type    新闻类型:  1.普通新闻 直播 2.图片新闻 3.推荐普通新闻 4.小视频 5.电商 6.图文 7.互动 8.链接 9.内容 10.乡镇
     *                11.政务 12.专题 13.电台音频 14.电视视频
     *                <p>
     *                15.圈子 16.cms视频新闻 17.开票有喜 8.开票有喜(底部)
     * @param summary 描述
     * @param title   标题
     * @param img     图片
     * @param context 上下文对象
     */
    public void goShare(final String newsId, final int type, final String summary, final String title, final String img, final Context context) {
        getShareUrl(newsId, type, new ShareCallBack() {
            @Override
            public void getUrlCallBack(boolean isSuccess, String jsonShare) {
                if (isSuccess) {
                    String shareTitle = "";
                    if (type == 11 || type == 10) {
                        shareTitle = title + "-" + context.getResources().getString(R.string.app_name);
                    } else {
                        shareTitle = title;
                    }
                    doShare((Activity) context, jsonShare, shareTitle, img, summary, new UMShareListener() {
                        @Override
                        public void onStart(SHARE_MEDIA share_media) {

                        }

                        @Override
                        public void onResult(SHARE_MEDIA share_media) {
                            Log.i("@@@", "33334");
                            ActionLogUtils.getInstance().doShare(title, type + "", newsId);
                            String userName = CommonUtils.getInstance().getUserName();
                            String integralSwitch = (String) AppConfigUtil.getInstance().getConValue(AppConfigConstant.INTEGRAL_SWITCH);
                            if (integralSwitch.equals("1") && Hawk.contains("login") && StringUtils.isNotEmpty(userName) && (type == 1 || type == 2 || type == 3 || type == 16)) {
                                getShareCoin(context);
                            } else {
                                Toasty.normal(context, "分享成功！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                            Toasty.normal(context, "分享失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onCancel(SHARE_MEDIA share_media) {
                            Toasty.normal(context, "分享取消！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    Toasty.normal(context, "当前分享链接异常！", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void goSingleShare(final String style, final String newsId, final int type, final String summary, final String title, final String img, final Context context) {

        getShareUrl(newsId, type, new ShareCallBack() {
            @Override
            public void getUrlCallBack(boolean isSuccess, String jsonShare) {
                if (!isSuccess) {
                    Toasty.normal(context, "当前分享链接异常！", Toast.LENGTH_SHORT).show();
                } else {
                    doSingleShare(style, (Activity) context, jsonShare, title, img, summary, new UMShareListener() {
                        @Override
                        public void onStart(SHARE_MEDIA share_media) {
                        }

                        @Override
                        public void onResult(SHARE_MEDIA share_media) {
                            String userName = CommonUtils.getInstance().getUserName();
                            ActionLogUtils.getInstance().doShare(title, type + "", newsId);
                            String integralSwitch = (String) AppConfigUtil.getInstance().getConValue(AppConfigConstant.INTEGRAL_SWITCH);
                            if (integralSwitch.equals("1") && Hawk.contains("login") && StringUtils.isNotEmpty(userName) && (type == 1 || type == 2 || type == 3 || type == 16)) {
                                getShareCoin(context);
                            } else {
                                Toasty.normal(context, "分享成功！", Toast.LENGTH_SHORT).show();
                            }
                            //四川融媒统计
                            if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
                                int channelId;
                                if (type == 1 || type == 2 || type == 16) {
                                    switch (style) {
                                        case "QQ":
                                            channelId = 2;
                                            break;
                                        case "WeiXin":
                                        case "Circle":
                                            channelId = 0;
                                            break;
                                        default:
                                            channelId = 3;
                                            break;
                                    }
                                    StatisticsMainInit.shareLog(CommonUtils.getInstance().getUserName(), newsId, title, channelId);
                                }
                            }
                        }

                        @Override
                        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                            Toasty.normal(context, "分享失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onCancel(SHARE_MEDIA share_media) {
                            Toasty.normal(context, "分享取消！", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    public void goSingleShare(final String style, final String newsId, final String contentId, final int type, final String summary, final String title, final String img, final Context context) {

        getShareUrl(newsId, contentId, type, new ShareCallBack() {
            @Override
            public void getUrlCallBack(boolean isSuccess, String jsonShare) {
                if (!isSuccess) {
                    Toasty.normal(context, "当前分享链接异常！", Toast.LENGTH_SHORT).show();
                } else {
                    doSingleShare(style, (Activity) context, jsonShare, title, img, summary, new UMShareListener() {
                        @Override
                        public void onStart(SHARE_MEDIA share_media) {
                        }

                        @Override
                        public void onResult(SHARE_MEDIA share_media) {
                            String userName = CommonUtils.getInstance().getUserName();
                            ActionLogUtils.getInstance().doShare(title, type + "", newsId);
                            String integralSwitch = (String) AppConfigUtil.getInstance().getConValue(AppConfigConstant.INTEGRAL_SWITCH);
                            if (integralSwitch.equals("1") && Hawk.contains("login") && StringUtils.isNotEmpty(userName) && (type == 1 || type == 2 || type == 3 || type == 16)) {
                                getShareCoin(context);
                            } else {
                                Toasty.normal(context, "分享成功！", Toast.LENGTH_SHORT).show();
                            }
                            //四川融媒统计
                            if (CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145) {
                                int channelId;
                                if (type == 1 || type == 2 || type == 16) {
                                    switch (style) {
                                        case "QQ":
                                            channelId = 2;
                                            break;
                                        case "WeiXin":
                                        case "Circle":
                                            channelId = 0;
                                            break;
                                        default:
                                            channelId = 3;
                                            break;
                                    }
                                    StatisticsMainInit.shareLog(CommonUtils.getInstance().getUserName(), newsId, title, channelId);
                                }
                            }
                        }

                        @Override
                        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                            Toasty.normal(context, "分享失败！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onCancel(SHARE_MEDIA share_media) {
                            Toasty.normal(context, "分享取消！", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    /**
     * 获取金币
     *
     * @param context
     */
    private void getShareCoin(final Context context) {
        intergralService.gainCoin("5", "gainCoin", new IntergralService.GainCoinCallBack() {
            @Override
            public void success(CoinBean coinBean) {
                Toasty.normal(context, "成功分享，获得" + coinBean.getCoin() + "金币！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void error(String msg) {
                Log.e("error_share", msg);
            }
        });

    }


    /**
     * 获取分享连接回调
     */
    public interface ShareCallBack {
        void getUrlCallBack(boolean isSuccess, String jsonShare);
    }

}
